import socket
import time

allServers = []

SERVERLISTPORT = 12321

sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
sock.bind( ("", SERVERLISTPORT) )

def ed(data):
	return bytes(str(data), 'UTF-8')

def dd(data):
	return eval(data.decode('UTF-8'))

while 1:
	(data, addr) = sock.recvfrom(2048)
	data = dd(data)
	
	global allServers

	if data["type"] == "get":
		allServers = [s for s in allServers if time.time() - s["timestamp"] < 60]
		ret = ed({"type":"serverlist", "data":allServers})
		sock.sendto(ret, addr)



	if data["type"] == "register":
		found = False
		for s in allServers:
			if s["ip"] == addr[0]:
				found = True
				s["name"] = data["name"]
				s["timestamp"] = time.time()


		if not found:
			allServers.append( {"ip":addr[0], "name":data["name"], "timestamp":time.time()} )
			
		print(allServers)